package com.shuke.medical.insure.remote;

import com.alibaba.fastjson.JSONObject;
import com.shuke.medical.insure.component.DataHandler;
import com.shuke.medical.insure.config.ChsProperties;
import com.shuke.medical.insure.eums.ChsInfNoEnum;
import com.shuke.medical.insure.remote.consts.ChsCacheConst;
import com.shuke.medical.insure.utils.SignUtil;
import com.tencent.mip.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/***
 * @title ChsPayRemoteHttp
 * @description
 * @author woo hua
 * @version 1.0.0
 * @create 2023/4/3 11:03
 **/
@Slf4j
@Component
public class ChsPayRemoteHttp {

    @Resource
    private ChsProperties chsProperties;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private ChsRemoteHttp chsRemoteHttp;

    /**
     * 加解密版
     *
     * @param infNo
     * @param jsonObject
     * @return
     * @throws Exception
     */
    public JSONObject doPost(ChsInfNoEnum infNo, JSONObject jsonObject) throws Exception {
        // 如果没有登录，就先登录
        if (!redisTemplate.hasKey(ChsCacheConst.CHS_SIGN_NO)) {
            chsRemoteHttp.signNo();
        }

        String appSecret = chsProperties.getPay().getAppSecret();
        String appId = chsProperties.getPay().getAppId();
        String publicKey = chsProperties.getPay().getPublicKey();
        String privateKey = chsProperties.getPay().getPrivateKey();
        String pubKey = chsProperties.getPay().getPubKey();
        String reqUrl = chsProperties.getPay().getReqUrl()
                .replace("{suffix}", infNo.getSuffix());
        log.info("请求地址: [{}]" + reqUrl);
        // 初始化
        DataHandler dataHandler = DataHandler.newInstance(appId, appSecret, publicKey,
                privateKey, pubKey);
        // // 请根据各个省市中台⽂档中，公共参数version设定。默认为2.0.0
        dataHandler.setVersion(chsProperties.getPay().getVersion());
        dataHandler.setSkipVerify(chsProperties.getPay().getSkipVerify());
        String reqData = dataHandler.buildReqData(jsonObject);
        // 请求局⽅接⼝的报⽂
        log.info("请求局⽅接⼝的报⽂: [{}]", reqData);

        HttpUtil httpUtil = new HttpUtil();
        // 请求头
        Map<String, String> requestHeader = buildRequestHeader();

        String str2 = httpUtil.postDataWithHeader(reqUrl, reqData, requestHeader);
        String rspData = dataHandler.processRspData(str2);

        // 验签解密后的报⽂
        log.info("验签解密后的报⽂: [{}]", rspData);
        return JSONObject.parseObject(rspData);
    }

    private Map<String, String> buildRequestHeader() {
        HashMap<String, String> header = new HashMap<>();
        header.put("Content-Type", "application/json");
        header.put("Accept", "application/json;charset=UTF-8");

        String passId = chsProperties.getPassId();
        String secretKey = chsProperties.getSecretKey();

        // 非重复的随机字符串（并非定长100位，十分钟内不能重复）。
        String xRioNonce = SignUtil.getRandomString(32);
        // 当前 unix 时间戳（秒）。
        String xRioTimestamp = String.valueOf(SignUtil.getCurrentUnixSeconds());
        // Sha256加密生成的签名。x-tif-signature = sha256(x-tif-timestamp + secretKey+ x-tif-nonce + xtif-timestamp)
        String signature = SignUtil.getSHA256Str(xRioTimestamp + secretKey + xRioNonce + xRioTimestamp);

        header.put("x-tif-paasid", passId);
        header.put("x-tif-signature", signature);
        header.put("x-tif-timestamp", xRioTimestamp);
        header.put("x-tif-nonce", xRioNonce);
        return header;
    }
}
